<?php
declare (strict_types = 1);

namespace app\admin\controller;
use think\facade\View;
use think\facade\Db;
use \app\common\Time;
class Login extends \app\admin\Base
{
  public function doLogin()
  {
    $account = input('username');
    $password = input('password');

    if (!$password  || !$account) {
      return $this->doError('登陆账号或密码不能为空');
    }

    $ck = Db::name('admin')
                  ->where('account',$account)
                  ->where('password',md5($password))
                  ->find();
    if ($ck) {
      if (!$ck['status']) {
        return $this->doError('该账户已被禁止登陆');
      }
      
      $log = array();
      $dutime = Time::daysAgo(7);
      $token = md5($password.time());
      if ($ck['token_time'] < $dutime) {
        $log['token'] = $token;
      }else{
        $log['token'] = $token;
      }
      $log['last_time'] = $ck['login_time'];
      $log['last_ip'] = $ck['login_ip'];
      $log['logins'] = $ck['logins']+1;
      $log['login_time'] = time();
      $log['token_time'] = time();
      $log['login_ip'] =  $_SERVER["REMOTE_ADDR"];
      Db::name('Admin')->where('id',$ck['id'])->update($log);
      $r['accessToken'] = $token;
      return $this->doSuccess('登陆成功',$r);
    }else{
      return $this->doError('登陆账号或密码错误');
    }

    $r['accessToken'] = 'admin-accessToken';
    return $this->doSuccess('success',$r);
  }

  public function logout()
  {
    return $this->doSuccess('success');
  }
  
}
